//
//  YXWorkPlanViewController.m
//  跑跑快销
//
//  Created by 杨潇 on 14-5-5.
//  Copyright (c) 2014年 ylife. All rights reserved.
//

#import "YXWorkPlanViewController.h"
#import "YXCalendarView.h"
#import "YXWorkSummarizeViewController.h"

@interface YXWorkPlanViewController ()

@end

@implementation YXWorkPlanViewController

- (void)dealloc
{
    [_dayBackBtn removeFromSuperview];
    [_datePickerBG removeFromSuperview];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self isAlarmClockWithDateStr:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _workPlanVi = [[YXWorkPlanView alloc] init];
    self.view = _workPlanVi;
    UIBarButtonItem * finishBtn = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleBordered target:self action:@selector(touchFinishBtn)];
    self.navigationItem.rightBarButtonItem = finishBtn;
    
    [_workPlanVi.datebtn addTarget:self action:@selector(touchDateBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_workPlanVi.alarmSwitch addTarget:self action:@selector(touchAlarmSwitch:) forControlEvents:UIControlEventValueChanged];
    for (int i = 0; i < 2; i ++) {
        UIButton * upBtn = (UIButton *)[_workPlanVi viewWithTag:i + 1];
        [upBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    _workPlanVi.textVi.delegate = self;
    [self isAlarmClockWithDateStr:nil];
}

- (void)isAlarmClockWithDateStr:(NSString *)dateStr
{
    NSMutableDictionary * infoDic = [NSMutableDictionary dictionaryWithContentsOfFile:[self getFileName]];
    if (infoDic) {
        NSString * alarmDate;
        if (dateStr) {
            alarmDate = [infoDic objectForKey:dateStr];
        }else{
            alarmDate = [infoDic objectForKey:[self getKeyName]];
        }
        if (alarmDate) {
            [_workPlanVi.alarmSwitch setOn:YES animated:YES];
        }else{
            [_workPlanVi.alarmSwitch setOn:NO animated:YES];
        }
    }else{
        [_workPlanVi.alarmSwitch setOn:NO animated:YES];
    }
}

- (NSString *)getFileName
{
    NSString * dateStr = _workPlanVi.datebtn.titleLabel.text;
    NSString * fileName = [self getPathWirhYMD:[dateStr substringToIndex:7]];
    return fileName;
}

- (NSString *)getKeyName
{
    NSString * ymd = _workPlanVi.datebtn.titleLabel.text;
    return ymd;
}

- (NSString *)getPathWirhYMD:(NSString *)ymd
{
    NSString * alarmClockPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/AlarmClock"];
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:alarmClockPath]) {
        [manager createDirectoryAtPath:alarmClockPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * path = nil;
    if (ymd) {
         path = [alarmClockPath stringByAppendingPathComponent:ymd];
    }else{
         path = [alarmClockPath stringByAppendingPathComponent:_workPlanVi.datebtn.titleLabel.text];
    }
    return path;
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0) {
        _workPlanVi.placeholderLab.hidden = NO;
    }else{
        _workPlanVi.placeholderLab.hidden = YES;
    }
}

#pragma mark - ButtonsClick
- (void)touchFinishBtn
{
    if (_alarmDateStr) {
        NSMutableDictionary * alarmDic = [NSMutableDictionary dictionaryWithContentsOfFile:[self getFileName]];
        if (!alarmDic) {
            alarmDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:_alarmDateStr,[self getKeyName], nil];
        }else{
            NSString * idStr = [alarmDic objectForKey:[self getKeyName]];
            if (idStr) {
                for (UILocalNotification * localNoti in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
                    if ([[localNoti.userInfo objectForKey:@"id"] isEqualToString:idStr]) {
                        [[UIApplication sharedApplication] cancelLocalNotification:localNoti];
                        break;
                    }
                }
            }
            [alarmDic setObject:_alarmDateStr forKey:[self getKeyName]];
        }
        [alarmDic writeToFile:[self getFileName] atomically:YES];
        
        NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        UILocalNotification * localNoti = [[UILocalNotification alloc] init];
        localNoti.fireDate = [formatter dateFromString:_alarmDateStr];
        localNoti.alertBody = [NSString stringWithFormat:@"跑跑快销闹钟提示：请查看您%@定的工作计划。",_alarmDateStr];
//        localNoti.soundName = UILocalNotificationDefaultSoundName;
        localNoti.soundName = @"cnhk.m4r";
        localNoti.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:_alarmDateStr,@"id",[self getKeyName],@"key",[self getFileName],@"path", nil];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
    }
}

- (void)touchDayBackBtn
{
    _dayBackBtn.hidden = YES;
}

- (void)touchDateBtn:(UIButton *)btn
{
    if (!_dayBackBtn) {
        UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:0];
        _dayBackBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _dayBackBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.3];
        _dayBackBtn.frame = [UIScreen mainScreen].bounds;
        [_dayBackBtn addTarget:self action:@selector(touchDayBackBtn) forControlEvents:UIControlEventTouchUpInside];
        [window addSubview:_dayBackBtn];
        
        YXCalendarView * dayCalendar = [[YXCalendarView alloc] initWithFrame:CGRectMake(0, btn.frame.origin.y + btn.frame.size.height + STARTY, 320, 325) withBlock:^(NSString * str) {
            [_workPlanVi.datebtn setTitle:str forState:UIControlStateNormal];
            _dayBackBtn.hidden = YES;
            [self isAlarmClockWithDateStr:str];
        }];
        [_dayBackBtn addSubview:dayCalendar];
    }
    _dayBackBtn.hidden = NO;
}

- (void)touchAlarmSwitch:(UISwitch *)swt
{
    if (swt.on) {
        [[YXWindowAlertView sharedWindowAlert] showLableWithTitle:@"请先点击“定时选择”按钮选择提醒时间"];
        [swt setOn:NO animated:YES];
    }else{
        NSMutableDictionary * infoDic = [NSMutableDictionary dictionaryWithContentsOfFile:[self getFileName]];
        if (infoDic) {
            NSString * alarmDate = [infoDic objectForKey:[self getKeyName]];
            if (alarmDate) {
                for (UILocalNotification * localNoti in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
                    NSString * idStr = [localNoti.userInfo objectForKey:@"id"];
                    if ([idStr isEqualToString:alarmDate]) {
                        [[UIApplication sharedApplication] cancelLocalNotification:localNoti];
                        break;
                    }
                }
                [infoDic removeObjectForKey:[self getKeyName]];
                [infoDic writeToFile:[self getFileName] atomically:YES];
            }
        }
        if (_alarmDateStr) {
            _alarmDateStr = nil;
        }
    }
}

- (void)btnClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 1:
        {
            YXWorkSummarizeViewController * workSummarizeVC = [[YXWorkSummarizeViewController alloc] init];
            workSummarizeVC.title = @"工作总结";
            [self setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:workSummarizeVC animated:YES];
        }
            break;
        case 2:
        {
            if (!_datePickerBG) {
                UIWindow * window = [[UIApplication sharedApplication].windows objectAtIndex:0];
                _datePickerBG = [UIButton buttonWithType:UIButtonTypeSystem];
                [_datePickerBG addTarget:self action:@selector(touchDatePickerBGBtn) forControlEvents:UIControlEventTouchUpInside];
                _datePickerBG.backgroundColor = [UIColor lightGrayColor];
                _datePickerBG.frame = [UIScreen mainScreen].bounds;
                [window addSubview:_datePickerBG];
                
                _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, 100, 300, 200)];
                _datePicker.locale = [NSLocale systemLocale];
                _datePicker.datePickerMode = UIDatePickerModeTime;
                [_datePickerBG addSubview:_datePicker];
                
                UIButton * confirmBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
                confirmBtn.frame = CGRectMake(10, _datePicker.frame.origin.y + _datePicker.frame.size.height + 10, 300, 30);
                confirmBtn.backgroundColor = [UIColor whiteColor];
                [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
                [confirmBtn addTarget:self action:@selector(touchConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
                [_datePickerBG addSubview:confirmBtn];
            }
            _datePickerBG.hidden = NO;
        }
            break;
            
        default:
            break;
    }
}

- (void)touchDatePickerBGBtn
{
    _datePickerBG.hidden = YES;
}

- (void)touchConfirmBtn
{
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    _alarmDateStr = [[_workPlanVi.datebtn.titleLabel.text stringByAppendingString:[NSString stringWithFormat:@" %@",[formatter stringFromDate:_datePicker.date]]] copy];
    _datePickerBG.hidden = YES;
    [_workPlanVi.alarmSwitch setOn:YES animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
